package com.zzxy.spring12.aspect;

import com.zzxy.spring12.service.ITeacherService;
import com.zzxy.spring12.service.impl.TeacherServiceImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

public class MyBeanFactoryCglib {
    public static ITeacherService createTeacherService() {
        // 1.target class
        ITeacherService teacherService = new TeacherServiceImpl();
        //2. advice
        MyAspect aspect = new MyAspect();
       /* //3. weaving > teacherServiceProxy
        ITeacherService proxy = (ITeacherService) Proxy.newProxyInstance(MyBeanFactoryCglib.class.getClassLoader(), teacherService.getClass().getInterfaces(),
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        aspect.before();
                        Object obj = method.invoke(teacherService, args);
                        aspect.after();
                        return obj;
                    }
                });*/
//3.enhancer
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(teacherService.getClass());
        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
                aspect.before();
                Object obj = methodProxy.invokeSuper(proxy, args);
                aspect.after();
                return obj;
            }
        });
        TeacherServiceImpl proxy = (TeacherServiceImpl) enhancer.create();
        return proxy;
    }
}
